<template>
  <div class="pagination">
    <button :disabled="pageNo === 1" @click='sendPage(pageNo - 1)'>上一页</button>
    <button v-show="startEnd.start > 1" @click='sendPage( 1)' :class="{active : pageNo === 1}">1</button>
    <span v-show="startEnd.start > 2">···</span>

    <button v-for="(item,index) in startEnd.end" :key="index" v-show="item >= startEnd.start" @click="sendPage(item)"
            :class="{active:item === pageNo}"
    >{{
        item
      }}
    </button>

    <span v-show="startEnd.end < totalPage - 1">···</span>

    <!--总共几页-->
    <button v-show="startEnd.end < totalPage" @click="sendPage(totalPage)">{{ totalPage }}</button>
    <button :disabled="pageNo === totalPage" @click="sendPage(pageNo + 1)">下一页</button>

    <span>{{ total }}</span>
  </div>
</template>

<script>
export default {
  name: 'SphPagination',
  props: {
    // 总数据
    total: {
      type: Number,
      require: true
    },
    // 每页展示多少
    pageSize: {
      type: Number,
      default: 5
    },
    // 当前页码
    pageNo: {
      type: Number,
      default: 1
    },
    // 当前页码连续数
    continues: {
      type: Number,
      default: 5
    }
  },
  computed: {
    // 计算一共几页
    totalPage () {
      return Math.ceil(this.total / this.pageSize)
    },
    // 计算起始页和结束页
    startEnd () {
      const {
        totalPage,
        pageNo,
        continues
      } = this
      let start = 0
      let end = 0
      if (continues > totalPage) {
        start = 1
        end = totalPage
      } else {
        // 起始数字
        start = pageNo - parseInt(continues / 2)
        end = pageNo + parseInt(continues / 2)
        if (start < 1) {
          start = 1
          end = continues
        }
        if (end > totalPage) {
          end = totalPage
          start = totalPage - continues - 1
        }
      }
      return {
        start,
        end
      }
    }
  },
  methods: {
    sendPage (page) {
      this.$emit('sendPage', page)
    }
  }
}
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;

  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: gray;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }

  span {
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>
